package base;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.io.IOException;
import java.util.HashMap;

/**
 * @Auther DRevelation
 * @Date 2020-06-08 上午 9:39
 * @Desc
 */
public class JacksonDemo {
    public static void main(String[] args) throws IOException {
        Person p = new Person();
        p.setName("解析json");
        p.setAge(11);
        p.setGender("男");

        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(p);

        System.out.println(p);
        System.out.println(s);

        String json = "{\"error\":0,\"data\":{\"name\":\"ABC\",\"age\":20,\"phone\":{\"home\":\"abc\",\"mobile\":\"def\"},\"friends\":[{\"name\":\"DEF\",\"phone\":{\"home\":\"hij\",\"mobile\":\"klm\"}},{\"name\":\"GHI\",\"phone\":{\"home\":\"nop\",\"mobile\":\"qrs\"}}]},\"other\":{\"nickname\":[]}}";

        HashMap map = mapper.readValue(json, HashMap.class);
        System.out.println(map.get("data"));

        JsonNode node = mapper.readTree(json);
        System.out.println(node.get("data").get("phone").get("home"));

        JsonNode mobile1 = node.get("data").get("friends").get(0).get("phone").get("mobile");
        System.out.println(mobile1);
    }
}

@Data
class Person {
    private String name;
    private int age;
    private String gender;
}
